import { useContext, useEffect } from "react";
import GanttContext from "../context";
import type { TaskMode } from "../types";
import { cn } from "../../../lib/utils";
import { GanttConsts } from "../constants";
import { getGanttWidth } from "../helpers/time";
import { PanelLeftClose } from "../components/icons";

interface TaskHeaderProps {
  title: string;
}
const ModeButton = ({ mode }: { mode: string }) => {
  const { taskMode, setTaskMode, setScrollLeft } = useContext(GanttContext);
  return (
    <div
      key={mode}
      className={cn(
        "h-8 w-16 flex justify-center items-center text-sm rounded-sm cursor-pointer",
        {
          "bg-orange-500 text-gray-50": mode === taskMode,
          "hover:bg-orange-50 hover:text-gray-500": mode !== taskMode,
        }
      )}
      onClick={() => {
        setTaskMode(mode as TaskMode);
        setScrollLeft(0);
      }}
    >
      {mode}
    </div>
  );
};

export default function TaskHeader({ title }: TaskHeaderProps) {
  const {
    hideTaskTable,
    setHideTaskTable,
    taskMode,
    tasksEnd,
    tasksStart,
    setGanttWidth,
  } = useContext(GanttContext);

  // 获取任务当前taskMode下的时间宽度
  useEffect(() => {
    const width = getGanttWidth(tasksStart, tasksEnd, taskMode);
    setGanttWidth(width);
  }, [setGanttWidth, taskMode, tasksEnd, tasksStart]);
  return (
    <div
      className="flex rounded-t-sm justify-between px-2 z-20 border"
      style={{
        height: `${GanttConsts.HEADER_HEIGHT}px`,
      }}
    >
      <div className="flex items-center pl-8">{title}</div>
      <div className="flex items-center gap-2">
        <div
          className={cn({
            "flex justify-center items-center rounded-sm h-8 w-8 bg-gray-100 border cursor-pointer":
              true,
            "rotate-180 bg-gray-50": !hideTaskTable,
          })}
          onClick={() => setHideTaskTable(!hideTaskTable)}
        >
          <PanelLeftClose className="text-orange-500" />
        </div>
        {GanttConsts.TASK_MODE.map((mode) => (
          <ModeButton key={mode} mode={mode} />
        ))}
      </div>
    </div>
  );
}
